package com.xyz.update.update

import android.content.Context
import android.content.pm.ActivityInfo
import android.media.MediaScannerConnection
import android.text.TextUtils
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SizeUtils
import com.google.gson.GsonBuilder
import java.math.RoundingMode
import java.text.DecimalFormat

/**
 * @auth zh
 * @time 2021/11/11 - 17:52
 * @desc 扩展函数
 */
class CommonExp {}

val gson = GsonBuilder().disableHtmlEscaping().create()

/**
 * 四种像素转换
 */
val Number.dp2px: Int get() = SizeUtils.dp2px(this.toFloat())
val Number.px2dp: Int get() = SizeUtils.px2dp(this.toFloat())
val Number.sp2px: Int get() = SizeUtils.sp2px(this.toFloat())
val Number.px2sp: Int get() = SizeUtils.px2sp(this.toFloat())

/**
 * 获取颜色
 */
fun Context.color(color: Int): Int = ContextCompat.getColor(this, color)

fun Int.color(): Int = ContextCompat.getColor(ActivityUtils.getTopActivity(), this)

/**
 * 获取文字
 */
fun Context.string(string: Int): String = this.resources.getString(string)

fun Int.string(): String = ActivityUtils.getTopActivity().resources.getString(this)

/**
 * 保留一位小数限制
 */
fun Double.oneDecimal(): String {
    val df = DecimalFormat("0.0")
    df.roundingMode = RoundingMode.HALF_UP
    return df.format(this)
}

fun String.oneDecimal(): String = this.toDouble().oneDecimal()

/**
 * 保留两位小数限制
 */
fun Double.twoDecimal(): String {
    val df = DecimalFormat("0.00")
    df.roundingMode = RoundingMode.HALF_UP
    return df.format(this)
}

fun String.twoDecimal(): String = this.toDouble().twoDecimal()

/**
 * 保留整数限制
 */
fun Double.noDecimal(): String {
    val df = DecimalFormat("0")
    df.roundingMode = RoundingMode.HALF_UP
    return df.format(this)
}

fun String.noDecimal(): String = this.toDouble().noDecimal()

/**
 * 必须 两位小数 或 整数
 */
fun Double.twoOrNoneDecimal(): String {
    val df = DecimalFormat("0.00")
    df.roundingMode = RoundingMode.HALF_UP
    var num: String = df.format(this)
    if (!TextUtils.isEmpty(num) && num.endsWith(".00")) {
        num = num.substring(0, num.length - 3)
    } else if (!TextUtils.isEmpty(num) && num.endsWith(".0")) {
        num = num.substring(0, num.length - 2)
    }
    return num
}

fun String.twoOrNoneDecimal(): String = this.toDouble().twoOrNoneDecimal()

//判断是不是竖屏状态
fun Context.activityIsPortrait(): Boolean =
    ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT == this.resources.configuration.orientation

//更新图库
fun Context.notifyGallery(path: String) {
    MediaScannerConnection.scanFile(this, arrayOf<String>(path), null, null)
}

fun List<String>.toVararg() = this.toTypedArray()
